package com.xoa.service.equipment.impl;

import com.alibaba.fastjson.JSONArray;
import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.equipment.*;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.department.Department;
import com.xoa.model.equipment.*;
import com.xoa.model.users.Users;
import com.xoa.service.equipment.EquipBorrowService;
import com.xoa.util.AjaxJson;
import com.xoa.util.LimsJson;
import com.xoa.util.UserUtil;
import com.xoa.util.common.StringUtils;
 import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class EquipBorrowServiceImpl implements EquipBorrowService {

    @Autowired
    private LimsEquipLendMapper limsEquipLendMapper;

    //@Autowired
    //private LimsDeptExpMapper limsDeptExpMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private EquipmentMapper equipmentMapper;

    @Autowired
    private EquipTypeMapper equipTypeMapper;

    @Autowired
    private EquipCapyMapper equipCapyMapper;

    @Autowired
    private LimsEquipLendlistMapper limsEquipLendlistMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    //@Autowired
    //private  LimsBaseService limsBaseService;

    @Autowired
    private LimsCommonCodeMapper limsCommonCodeMapper;

    @Autowired
    private  LimsEquipUselogMapper limsEquipUselogMapper;
    @Autowired
    private EquipmentTransferServiceImpl equipmentTransferService;

    @Autowired
    private SysCodeMapper sysCodeMapper;
    /** 创建作者:   王穗穗
     * 创建日期:   15:02 2019/10/8
     * 方法介绍:   查询设备借用数据
     */
    @Override
    public LimsJson getequipborrowing(HttpServletRequest request,Integer page, Integer limit,Map map,String ApprovalStatus,String column,String inptext)                                                                                                                                                          {
        LimsJson limsJson=new LimsJson();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(limit);
        map.put("page", pageParams);
        Users users= UserUtil.getUser(request);
        map.put("borrowerOperationUser",users.getUserId());
        map.put("approverStatus",ApprovalStatus);
        if(column!=null && inptext!=null){
            Map map2 = new HashMap();
            if( column.equals("BORROWER_USER") || column.equals("BORROWER_OPERATION_USER") || column.equals("APPROVER")){
                map2.put("userName",inptext);
                List<Users> usersList1 = usersMapper.selByUserNameAndDeptId(map2);
                String uids="";
                for(Users users2:usersList1){
                    uids+=users2.getUserId()+",";
                }
                String key=equipmentTransferService.lineToHump(column);

                map.put("column",column);
                map.put("smcolums",key);
                map.put("columsValue",uids.split(","));
            }  else if( column.equals("BORROWER_DETP_ID") || column.equals("LEND_DEPT_ID")){
                List<Department> departments = departmentMapper.selByLikeDeptName(inptext);
                String deptIdsArry="";
                for(Department department:departments){
                    deptIdsArry+=department.getDeptId()+",";
                }
                String key=equipmentTransferService.lineToHump(column);
                map.put("column",column);
                map.put("smcolums",key);
                map.put("columsValue",deptIdsArry.split(","));
            }else{
                map.put("column",column);
                map.put("inptext",inptext);
            }

        }
        List<LimsEquipLend> list=limsEquipLendMapper.selectByUserId(map);
        for(LimsEquipLend l:list){
            if (l.getBorrowerUser()!=null&&!l.getBorrowerUser().equals("")){  //借用人
                Users users1=usersMapper.findUsersByuserId(l.getBorrowerUser());
                if(users1!=null){
                    l.setBorrowerUser(users1.getUserName());
                }
            }
            if (l.getBorrowerOperationUser()!=null&&!l.getBorrowerOperationUser().equals("")){  //借用操作人
                Users users1=usersMapper.findUsersByuserId(l.getBorrowerOperationUser());
                if(users1!=null){
                    l.setBorrowerOperationUser(users1.getUserName());
                }
            }
            if (l.getBorrowerDetpId()!=null&&!l.getBorrowerDetpId().equals("")){  //借入部门
                Department  department=departmentMapper.getDeptById(l.getBorrowerDetpId());
                if(department!=null){
                    l.setBorrowerdeptName(department.getDeptName());
                }
            }
            if (l.getLendDeptId()!=null&&!l.getLendDeptId().equals("")){  //借出部门
                Department  department=departmentMapper.getDeptById(l.getLendDeptId());
                if(department!=null){
                    l.setLenddeptName(department.getDeptName());
                }
            }
            if(l.getApprover()!=null&&!l.getApprover().equals("")){
                Users users1=usersMapper.findUsersByuserId(l.getApprover());
                if(users1!=null){
                    l.setApprover(users1.getUserName());
                }
            }
        }
        if(list!=null){
            limsJson.setData(list);
            limsJson.setMsg("查询成功");
            limsJson.setCount(pageParams.getTotal());
        }else {
            limsJson.setMsg("暂无数据");
        }
        return limsJson;
    }


    /** 创建作者:   王穗穗
     * 创建日期:   16:41 2019/10/8
     * 方法介绍:   添加设备借用单
     * 参数说明:   [limsEquipLend]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson insertSelective(HttpServletRequest request, LimsEquipLend limsEquipLend,String lendListJson) {
        LimsJson limsJson=new LimsJson(1,"err");
        if(limsEquipLend!=null){
            Users users=UserUtil.getUser(request);
            limsEquipLend.setBorrowerOperationUser(users.getUserId());
            limsEquipLend.setReturnStatus("2");  //处理状态为 未归还状态
            limsEquipLend.setApproverStatus("0");  //审批状态为新建状态
            limsEquipLend.setBorrowOperationTime(new Date());
            int count=limsEquipLendMapper.insertSelective(limsEquipLend);
            if(count>0){
             /*   JSONArray lendListJsonArray = JSONArray.fromObject(lendListJson);
                List<LimsEquipLendlist> limsEquipLendList = (List<LimsEquipLendlist>) JSONArray.toCollection(lendListJsonArray, LimsEquipLendlist.class);*/

                List<LimsEquipLendlist> limsEquipLendList= JSONArray.parseArray(lendListJson,LimsEquipLendlist.class);
                String result="";
                for(LimsEquipLendlist l:limsEquipLendList){
                    l.setReturnStatus(0);
                    l.setLendId(limsEquipLend.getLendId());
                    int result1 = limsEquipLendlistMapper.insertSelective(l);
                }

                if(count>0){
                    limsJson.setCode(0);
                    limsJson.setMsg("添加成功");
                }else{
                    limsJson.setMsg("设备借用失败");
                }
            }else{
                limsJson.setMsg("设备借用失败");
            }
        }else{
            limsJson.setMsg("借用单数据不正确，无法借用设备");
        }
        return limsJson;
    }




    /** 创建作者:   王穗穗
     * 创建日期:   16:41 2019/10/8
     * 方法介绍:   借用部门查询
     * 参数说明:   [request]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson getorganization(HttpServletRequest request) {
        LimsJson limsJson=new LimsJson(1,"err");
        List<Department> list = departmentMapper.getAllDepartment();
        if (list!=null){
            limsJson.setCode(0);
            limsJson.setData(list);
            limsJson.setMsg("查询成功");
        }else{
            limsJson.setMsg("暂无数据");
        }
        return limsJson;
    }


    /** 创建作者:   王穗穗
     * 创建日期:   16:42 2019/10/8
     * 方法介绍:   查询借出部门结算组织
     * 参数说明:   [deptId]
     * @return     com.xoa.util.AjaxJson
     */
    @Override
    public AjaxJson getoneDepx(HttpServletRequest request,Integer deptId){
        AjaxJson ajaxJson=new AjaxJson();
        //LimsDeptExp limsDeptExp=limsDeptExpMapper.getDeptExpId(deptId);
        if(deptId!=null) {
            Department department=departmentMapper.getDeptById(deptId);
            List<Department> departments=new ArrayList<>();
            departments.add(department);
            ajaxJson.setTotleNum(1);
            ajaxJson.setObj(departments);
            ajaxJson.setMsg("查询成功");
            ajaxJson.setFlag(true);
        }
        return ajaxJson;
    }


    /** 创建作者:   王穗穗
     * 创建日期:   17:01 2019/10/8
     * 方法介绍:   查询借出部门下的设备
     * 参数说明:   [request, equipTypeId, deptId]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson getequipmentBydeptid(HttpServletRequest request,Integer equipTypeId,Integer deptId,Integer page, Integer limit, String searchcloumn,String searchValue){
        LimsJson limsJson = new LimsJson(1,"查询失败");
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(limit);
        Map map=new HashMap();
        Map map1=new HashMap();
        map.put("page", pageParams);
        map.put("deptId",deptId);
        map1.put("deptId",deptId);
        List<EquipType> equipTypeList = equipTypeMapper.selectChildEquipType(equipTypeId);  //查询有没有子类型
        String[] status=new String[]{"EQUIP_INTACT","EQUIP_LEND"};    //只查询设备状态属于完好和借出状态的设备
        map.put("smcolums","status");   //用于进入sql中的If条件
        map.put("columsValue",status);
        map.put("column","EQUIP_STATUAS_CODE");
        map1.put("smcolums","status");   //用于进入sql中的If条件
        map1.put("columsValue",status);
        map1.put("column","EQUIP_STATUAS_CODE");
        if(searchcloumn!=null&&searchcloumn.equals("EQUIP_STATUAS_CODE")){   //模糊查询如果查寻设备状态，需要特殊处理
            map.put("type",searchValue);
            map1.put("type",searchValue);
            List<SysCode> sysCodes = sysCodeMapper.searchList(map);
            String types="";
            if(sysCodes.size()>0){
                for(SysCode l:sysCodes){
                    types+=l.getCodeNo()+",";
                }
                map.put("foreachColumn","1");
                map.put("searchcloumn",searchcloumn);
                map.put("searchValue",types.split(","));
                map1.put("foreachColumn","1");
                map1.put("searchcloumn",searchcloumn);
                map1.put("searchValue",types.split(","));
            }
        }else{
            if(searchcloumn!=null&&!searchcloumn.equals("SPEC")&&!searchcloumn.equals("MODEL_NO")&&!searchcloumn.equals("EQUIP_NAME")){
                limsJson.setMsg("参数错误");
                return limsJson;
            }
            map.put("searchcloumn",searchcloumn);   //模糊查询的字段名
            map.put("searchValue",searchValue);   //模糊查询的值
            map1.put("searchcloumn",searchcloumn);   //模糊查询的字段名
            map1.put("searchValue",searchValue);   //模糊查询的值
        }
        if(equipTypeList.size()>0){   //该类型下是否有子级
            String ids=equipTypeId+",";
            for (EquipType equipType:equipTypeList){
                ids=ids+equipType.getId()+",";
            }
            if (ids.length()>0){
                String[] typeIds = ids.split(",");
                map.put("typeIds",typeIds);
                map1.put("typeIds",typeIds);
            }
        }else{
            map.put("equipTypeId",equipTypeId);
            map1.put("equipTypeId",equipTypeId);
        }
        List<Equipment> equipment = equipmentMapper.selectAllEquipment(map);
        int count=equipmentMapper.countAllEquipment(map1);
        try {
            for (Equipment e:equipment){
                if(e.getEquipStatuasId()!=null&&!e.getEquipStatuasId().equals("")){
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getEquipStatuasId(),null);
                    if (equipCapy!=null&&!equipCapy.equals("")){
                        e.setEquipTypeCode(e.getEquipStatuasId());
                        e.setEquipStatuasId(equipCapy.getCodeTypeName());
                    }
                }
                if(e.getPhyQuantiId()!=null&&!e.getPhyQuantiId().equals("")){
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getPhyQuantiId(),null);
                    if(equipCapy!=null&&!equipCapy.equals("")){

                        e.setPhyQuantiId(equipCapy.getCodeTypeName());
                    }
                }
                if(e.getCouplingId()!=null&&!e.getCouplingId().equals("")){
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getCouplingId(),null);
                    if (equipCapy!=null&&!equipCapy.equals("")){
                        e.setCouplingId(equipCapy.getCodeTypeName());
                    }
                }
                if(e.getDirectionId()!=null&&!e.getDirectionId().equals("")){
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getDirectionId(),null);
                    if (equipCapy!=null&&!equipCapy.equals("")){
                        e.setDirectionId(equipCapy.getCodeTypeName());
                    }
                }
                if(e.getPropertyId()!=null&&!e.getPropertyId().equals("")){
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getPropertyId(),"PROPERTY_OWNER");
                    if (equipCapy!=null&&!equipCapy.equals("")){
                        e.setPropertyId(equipCapy.getCodeTypeName());
                    }
                }
                if(e.getSourceAssets()!=null&&!e.getSourceAssets().equals("")){
                    EquipCapy equipCapy = equipCapyMapper.selectCommonCodeByTypeNo(e.getSourceAssets(),null);
                    if (equipCapy!=null&&!equipCapy.equals("")){
                        e.setSourceAssets(equipCapy.getCodeTypeName());
                    }
                }
                if (e.getStandMateYn()!=null&&!e.getStandMateYn().equals("")){
                    if(e.getStandMateYn().equals("0")){
                        e.setStandMateYn("否");
                    }else {
                        e.setStandMateYn("是");
                    }
                }
            }
            for(Equipment e:equipment){
                if(e.getDeptId()!=null){
                    Department department=departmentMapper.getDeptById(e.getDeptId());
                    if(department!=null){
                        e.setDeptName(department.getDeptName());
                    }
                }
            }
            if(equipment.size()>0){
                limsJson.setCount(count);
                limsJson.setMsg("查询到"+count+"条数据");
                limsJson.setCode(0);
                limsJson.setData(equipment);
            }else{
                limsJson.setMsg("查询无数据");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return limsJson;
    }




    /** 创建作者:   王穗穗
     * 创建日期:   13:16 2019/10/9
     * 方法介绍:   单设备归还
     *
     * 参数说明:   [request, lendListId, equipId, returnUser]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public  LimsJson Returnquipborrowing(HttpServletRequest request,Integer lendListId,Integer equipId,String returnUser,Integer lendId){
        LimsJson limsJson=new LimsJson(1,"err");
        Map map=new HashMap();
        map.put("lendId",lendId);
        if(lendListId!=null&&equipId!=null&&returnUser!=null){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            Users users=UserUtil.getUser(request);
            LimsEquipLendlist limsEquipLendlist=new LimsEquipLendlist();
            limsEquipLendlist.setLendListId(lendListId);
            limsEquipLendlist.setReturnStatus(1);  //未归还 0、已归还 1',
            limsEquipLendlist.setReturnOperatorUser(users.getUserId());  //归还操作人
            limsEquipLendlist.setReturnUser(returnUser);  //归还人
            limsEquipLendlist.setReturnTime(df.format(new Date()));
            limsEquipLendlist.setEquipStatuasCode("EQUIP_INTACT");
            int count=limsEquipLendlistMapper.updateByPrimaryKeySelective(limsEquipLendlist);   //修改设备借还记录表状态
            if(count>0){   //修改设备借还单处理状态以及设备使用状态
                Integer returnStatus=1;
                map.put("returnStatus",returnStatus);
                List<LimsEquipLendlist> lendlistList=limsEquipLendlistMapper.select(map); //判断借用设备是否已有归还设备
                if(lendlistList.size()>0){
                    returnStatus=0;
                    map.put("returnStatus",returnStatus);
                    List<LimsEquipLendlist> l=limsEquipLendlistMapper.select(map);
                    if(l.size()<=0){  //设备单下的设备已经全部归回
                        returnStatus=0;     //全部归还
                    }else{
                        returnStatus=1;  //部分归还
                    }
                }else{
                    returnStatus=2;  //未归还
                }
                LimsEquipLend limsEquipLend=new LimsEquipLend();
                limsEquipLend.setLendId(lendId);
                limsEquipLend.setReturnStatus(returnStatus.toString());
                int count1=limsEquipLendMapper.updateByPrimaryKeySelective(limsEquipLend);
                if(count1>0) {
                    Equipment equipment = new Equipment();
                    equipment.setEquipId(equipId);
                    equipment.setEquipStatuasId("EQUIP_INTACT");   //已归还的设备状态修改完好状态
                    int result = equipmentMapper.updateByPrimaryKeySelective(equipment);
                    if (result > 0) {
                        limsJson.setMsg("归还成功");
                    } else {   //如果设备状态修改失败，则设备借还单还原数据
                        limsEquipLendlist.setReturnStatus(0);  //归还状态
                        limsEquipLendlist.setReturnOperatorUser("");  //归还操作人
                        limsEquipLendlist.setReturnUser("");  //归还人
                        limsEquipLendlist.setReturnTime("");
                        int result1 = limsEquipLendlistMapper.updateByPrimaryKey(limsEquipLendlist);
                        if (result1 > 0) {
                            limsJson.setMsg("设备归还失败");
                        }
                    }
                }else{  //设备借还单修改失败
                    limsEquipLendlist.setReturnStatus(0);  //归还状态
                    limsEquipLendlist.setReturnOperatorUser("");  //归还操作人
                    limsEquipLendlist.setReturnUser("");  //归还人
                    limsEquipLendlist.setReturnTime("");
                    int result1 = limsEquipLendlistMapper.updateByPrimaryKey(limsEquipLendlist);
                    if (result1 > 0) {
                        limsJson.setMsg("设备归还失败");
                    }
                }
            }else{
                limsJson.setMsg("设备归还失败");
            }
        }else{
            limsJson.setMsg("设备归还失败");
        }
        return limsJson;
    }



    /** 创建作者:   王穗穗
     * 创建日期:   14:18 2019/10/9
     * 方法介绍:   设备借还单归还操作
     * 参数说明:   [request, lengId, returnUser]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson Returnborrowing(HttpServletRequest request,Integer lendId,String returnUser) {
        LimsJson limsJson=new LimsJson();
        if(lendId!=null&&returnUser!=null){
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            Users users=UserUtil.getUser(request);
            LimsEquipLend limsEquipLend=new LimsEquipLend();
            limsEquipLend.setLendId(lendId);
            limsEquipLend.setReturnStatus("0");
            int count=limsEquipLendMapper.updateByPrimaryKeySelective(limsEquipLend);  //借还单状态修改
            if(count>0){
                LimsEquipLendlist limsEquipLendlist=new LimsEquipLendlist();
                limsEquipLendlist.setReturnTime(df.format(new Date()));
                limsEquipLendlist.setReturnStatus(1);
                limsEquipLendlist.setReturnUser(returnUser);
                limsEquipLendlist.setReturnOperatorUser(users.getUserId());
                limsEquipLendlist.setLendId(lendId);
                int result=limsEquipLendlistMapper.updateBylendId(limsEquipLendlist);
                Map map=new HashMap();
                map.put("lendId",lendId);
                List<LimsEquipLendlist> lendlists=limsEquipLendlistMapper.select(map);
                for(LimsEquipLendlist limsEquipLendlist1:lendlists){
                    if(limsEquipLendlist1.getEquipId()!=null) {
                        Equipment equipment = new Equipment();
                        equipment.setEquipId(limsEquipLendlist1.getEquipId());
                        equipment.setEquipStatuasId("EQUIP_INTACT");   //已归还的设备状态修改完好状态
                        equipmentMapper.updateByPrimaryKeySelective(equipment);
                    }
                }
                if(result>0){
                    limsJson.setMsg("归还成功");
                }else{
                    limsEquipLend.setReturnStatus("2");
                    int re=limsEquipLendMapper.updateByPrimaryKeySelective(limsEquipLend);  //借还单状态修改
                    if(re>0) {
                        limsJson.setMsg("归还失败");
                    }
                }
            }else{
                limsJson.setMsg("归还失败");
            }
        }else{
            limsJson.setMsg("归还失败");
        }
        return limsJson;
    }


    /** 创建作者:   王穗穗
     * 创建日期:   15:08 2019/10/9
     * 方法介绍:   设备借用单撤销
     * 参数说明:   [request, lengId]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson Revokequipborrowing(HttpServletRequest request, Integer lengId) {
        LimsJson limsJson=new LimsJson();
        if(lengId!=null){
            int i=0;
            Map map=new HashMap();
            map.put("lendId",lengId);
            map.put("returnStatus",1);
            List<LimsEquipLendlist> list=limsEquipLendlistMapper.select(map);  //判断是否有已归还设备
            if(list.size()>0){
                limsJson.setMsg("已有设备归还，无法撤销");
            }else {
                map.put("returnStatus",0);
                List<LimsEquipLendlist> lendlists=limsEquipLendlistMapper.select(map);  //判断是否有已归还设备
                for (LimsEquipLendlist l : lendlists) {
                    Equipment equipment = new Equipment();
                    equipment.setEquipId(l.getEquipId());
                    equipment.setEquipStatuasId("EQUIP_INTACT");   //已归还的设备状态修改完好状态
                    int count = equipmentMapper.updateByPrimaryKeySelective(equipment);
                    if (count <= 0) {
                        equipment.setEquipStatuasId("EQUIP_LEND");   //返回原数据
                        int result = equipmentMapper.updateByPrimaryKeySelective(equipment);
                        i = 0;
                        break;
                    } else {
                        i++;
                    }
                }
                if (i == 0) {
                    limsJson.setMsg("撤销失败");
                }else{
                    int r = limsEquipLendlistMapper.deleteBylendId(lengId);
                    if(r>0){
                        int a=limsEquipLendMapper.deleteByPrimaryKey(lengId);
                        if(a>0){
                            i=1;
                            limsJson.setMsg("撤销成功");
                        }else{  //设备单删除失败
                            i=0;
                            limsJson.setMsg("撤销失败");
                        }
                    }else{  //设备明细删除失败
                        i=0;
                    }
                    if(i==0){
                        for (LimsEquipLendlist l : lendlists) {
                            limsEquipLendlistMapper.insertSelective(l);  //还原设备明细表数据
                        }
                        for (LimsEquipLendlist l : lendlists) {
                            Equipment equipment = new Equipment();
                            equipment.setEquipId(l.getEquipId());
                            equipment.setEquipStatuasId("EQUIP_LEND");   //还原未点击撤销前设备表中状态数据
                            equipmentMapper.updateByPrimaryKeySelective(equipment);
                        }
                        limsJson.setMsg("撤销失败");
                    }
                }
            }
        }else{
            limsJson.setMsg("无法撤销设备");
        }
        return limsJson;
    }


    /** 创建作者:   王穗穗
     * 创建日期:   16:49 2019/10/9
     * 方法介绍:   添加设备明细
     * 参数说明:   [request, lendId, limsEquipLendlist]
     * @return     com.xoa.util.LimsJson
     */
    public LimsJson addlendList(HttpServletRequest request,String lendListJson){
        LimsJson limsJson=new LimsJson();
       /* JSONArray lendListJsonArray = JSONArray.fromObject(lendListJson);
        List<LimsEquipLendlist> limsEquipLendList = (List<LimsEquipLendlist>) JSONArray.toCollection(lendListJsonArray, LimsEquipLendlist.class);*/
        List<LimsEquipLendlist> limsEquipLendList= JSONArray.parseArray(lendListJson,LimsEquipLendlist.class);
        int i=0;
        String result2="";
        for(LimsEquipLendlist l:limsEquipLendList){
            Map map=new HashMap();
            map.put("equipId",l.getEquipId());
            map.put("lendId",l.getLendId());
            LimsEquipLendlist equipLendlist=limsEquipLendlistMapper.resultCult1(map);
            if(equipLendlist==null) {
                int a = limsEquipLendlistMapper.insertSelective(l);
                if (a > 0) {
                    i++;
                }
            }
            if(equipLendlist!=null){
                result2+=equipLendlist.getEquipName()+",";
            }
        }
        if(limsEquipLendList.size()!=i&&!result2.equals("")){
            limsJson.setMsg(result2+"设备已存在");
            return  limsJson;
        }
        if (limsEquipLendList.size()==i&&result2.equals("")){
            limsJson.setCode(0);
            limsJson.setMsg("添加成功");
        }else{
            limsJson.setMsg("添加失败");
        }
        return limsJson;
    }


    /** 创建作者:   王穗穗
     * 创建日期:   16:53 2019/10/9
     * 方法介绍:   删除设备明细
     * 参数说明:   [request, lendListId]
     * @return     com.xoa.util.LimsJson
     */
    public  LimsJson delLendList(HttpServletRequest request,String lendListId){
        LimsJson limsJson=new LimsJson();
        if(lendListId!=null){
            String[] id=lendListId.split(",");
            int count=0;
            for(String l:id){
                Integer lengList=Integer.parseInt(l);
                int i=limsEquipLendlistMapper.deleteByPrimaryKey(lengList);
                if(i>0){
                    count++;
                }
            }
            if(count>0){
                limsJson.setCode(0);
                limsJson.setMsg("删除成功");
            }else{
                limsJson.setMsg("删除失败");
            }
        }else{
            limsJson.setMsg("删除失败");
        }
        return limsJson;
    }



    /** 创建作者:   王穗穗
     * 创建日期:   17:00 2019/10/9
     * 方法介绍:   查询明细
     * 参数说明:   [lendId]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson getLendList(Integer lendId,Integer page, Integer limit,Map map) {
        LimsJson limsJson=new LimsJson();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(limit);
        map.put("page", pageParams);
        map.put("lendId",lendId);
        if(lendId!=null){
            List<LimsEquipLendlist> list=limsEquipLendlistMapper.select(map);
            for(LimsEquipLendlist l:list){
                if(l.getEquipStatuasCode()!=null){
/*
                    LimsCommonCode limsCommonCode=limsCommonCodeMapper.selectCodeTypeName(l.getEquipStatuasCode());
*/
                    SysCode sysCode = sysCodeMapper.selectCodeTypeName(l.getEquipStatuasCode());
                    l.setEquipStatuasCode(sysCode.getCodeName());
                }
                if(l.getReturnUser()!=null){
                    Users users=usersMapper.getUsersByuserId(l.getReturnUser());
                    l.setReturnUser(users.getUserName());
                }
            }
            if(list!=null){
                limsJson.setData(list);
                limsJson.setMsg("查询成功");
                limsJson.setCount(pageParams.getTotal());
            }else{
                limsJson.setMsg("暂无数据");
            }
        }else{
            limsJson.setMsg("暂无数据");
        }
        return limsJson;
    }


    /** 创建作者:   王穗穗
     * 创建日期:   13:42 2019/10/10
     * 方法介绍:   设备借用审批状态流
     * 参数说明:   [lendId]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson lendApprovalStatus(HttpServletRequest request,String lendId,String ApprovalStatus) {
        LimsJson limsJson=new LimsJson(1,"err");
        if(lendId!=null&& ApprovalStatus!=null){
            Users users=UserUtil.getUser(request);
            String[] lendstr=lendId.split(",");
            String[] Approvalatr=ApprovalStatus.split(",");
            if(lendstr.length==Approvalatr.length){
                int j=0;
                for(int i=0;i<lendstr.length;i++){
                    Integer lendIds=Integer.parseInt(lendstr[i]);
                    LimsEquipLend limsEquipLend=new LimsEquipLend();
                    limsEquipLend.setLendId(lendIds);
                    limsEquipLend.setApproverStatus(Approvalatr[i]);
                    if(Approvalatr[i].equals("1")){   //设备单提交
                        List<LimsEquipLendlist> list=limsEquipLendlistMapper.resulrApproval(lendIds);  //查询已经提交/批准并且未归还的设备
                        //查询设备是否已经被借出
                        List<Equipment> equipment=equipmentMapper.resultCode(lendIds);
                        String result="";
                        for(LimsEquipLendlist l:list){
                            result+=l.getEquipName()+",";
                        }
                        for (Equipment e:equipment){
                            result+=e.getEquipName()+",";
                        }
                        if(result.equals("")) {
                            //判断需要提交的设备是否属于该借出部门
                            List<Equipment> equipmentList=equipmentMapper.getdistant(lendIds);
                            LimsEquipLend lend=limsEquipLendMapper.selectByPrimaryKey(lendIds);
                            if(equipment.size()!=0&&!equipmentList.get(0).getDeptId().equals(lend.getLendDeptId())){
                                limsJson.setCode(0);
                                limsJson.setMsg("所借部门与设备不匹配");
                                return limsJson;
                            }else{
                                int count = limsEquipLendMapper.updateByPrimaryKeySelective(limsEquipLend);
                                if (count > 0) {
                                    j++;
                                } else {
                                    int a = limsEquipLendMapper.updateByPrimaryKeySelective(limsEquipLend);
                                    j = -1;
                                    break;
                                }
                            }
                        }else{
                            limsJson.setMsg(result+"设备已被人提交或使用，无法提交");
                            return  limsJson;
                        }
                    }else{  //设备单审批
                        limsEquipLend.setApprover(users.getUserId());
                        limsEquipLend.setApproverTime(new Date());
                        int count=limsEquipLendMapper.updateByPrimaryKeySelective(limsEquipLend);
                        if(Approvalatr[i].equals("2")){
                            if(count>0){
                                Map map=new HashMap();
                                map.put("lendId",Integer.parseInt(lendstr[i]));
                                List<LimsEquipLendlist> list=limsEquipLendlistMapper.select(map);
                                for(LimsEquipLendlist l:list){
                                    Integer equipId=l.getEquipId();
                                    LimsEquipLendlist limsEquipLendlist=new LimsEquipLendlist();
                                    limsEquipLendlist.setLendListId(l.getLendListId());
                                    limsEquipLendlist.setEquipId(equipId);
                                    limsEquipLendlist.setEquipStatuasCode("EQUIP_LEND");
                                    limsEquipLendlistMapper.updateByPrimaryKeySelective(limsEquipLendlist);
                                    Equipment equipment = new Equipment();
                                    equipment.setEquipId(equipId);
                                    equipment.setEquipStatuasId("EQUIP_LEND");    //批准后修改设备状态为借出
                                    int result = equipmentMapper.updateByPrimaryKeySelective(equipment);
                                }
                                j++;
                            }else {
                                j=-1;
                                LimsEquipLend lend=new LimsEquipLend();
                                limsEquipLend.setLendId(Integer.parseInt(lendstr[i]));
                                limsEquipLend.setApproverStatus("0");
                                int a=limsEquipLendMapper.updateByPrimaryKeySelective(lend);
                                break;
                            }
                        }
                    }
                }
                if(j!=-1){   //提示前端
                    limsJson.setCode(0);
                    limsJson.setMsg("提交成功");
                }else{
                    limsJson.setMsg("设备单无法提交，请核实借用设备数据");
                }
            }else{
                if(ApprovalStatus.substring(0,1).equals("1")) {
                    limsJson.setMsg("设备单无法提交，请核实借用设备数据");
                }else{
                    limsJson.setMsg("设备单无法审批，请核实借用设备数据");
                }
            }
        }else{
            if(ApprovalStatus.substring(0,1).equals("1")) {
                limsJson.setMsg("设备单无法提交，请核实借用设备数据");
            }else{
                limsJson.setMsg("设备单无法审批，请核实借用设备数据");
            }
        }
        return limsJson;
    }



    /** 创建作者:   王穗穗
     * 创建日期:   14:45 2019/10/10
     * 方法介绍:   删除设备单
     * 参数说明:   [lendId]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson  delLend(String lendId) {
        LimsJson limsJson=new LimsJson(1,"err");
        if(lendId!=null){
            String result;
            String[] lendstr=lendId.split(",");
            for(String l:lendstr){
                LimsEquipLend limsEquipLend=limsEquipLendMapper.selectByPrimaryKey(Integer.parseInt(l));
                if(limsEquipLend!=null){
                    if(limsEquipLend.getWorkflowNo()!=null){
                        limsJson.setMsg("设备借用单已有流水号，无法删除");
                    }else{
                        int count=limsEquipLendlistMapper.deleteBylendId(Integer.parseInt(l));   //删除设备借还明细表
                        int c=limsEquipLendMapper.deleteByPrimaryKey(Integer.parseInt(l));
                        if(c>0){
                            limsJson.setCode(0);
                            limsJson.setMsg("删除成功");
                        }else{
                            limsJson.setMsg("删除失败");
                        }

                    }
                }
            }

        }
        return limsJson;
    }



    /** 创建作者:   王穗穗
     * 创建日期:   15:57 2019/10/10
     * 方法介绍:     设备借还管理
     * 参数说明:   [request, page, limit, map, ApprovalStatus]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson getAdministration(HttpServletRequest request, Integer page, Integer limit, Map map, String ApprovalStatus,String column,String inptext) {
        LimsJson limsJson=new LimsJson(0,"err");
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(limit);
        Map map1=new HashMap();
        map.put("page", pageParams);
        Users users=UserUtil.getUser(request);
        List<Department> departments2 =null;
        //通过用户查找部门
        if(users!=null) {
            Integer deptId = users.getDeptId();
            String deptIdOther = users.getDeptIdOther();
            if (!StringUtils.checkNull(deptIdOther)) {
                deptIdOther = deptId + "," + deptIdOther;
            } else {
                deptIdOther = deptId + ",";
            }
            String[] deptIds = deptIdOther.split(",");

             departments2 = departmentMapper.selDeptByIds(deptIds);
        }
        //List<LimsDeptExp> limsDeptExpList=limsBaseService.baseGetDeptExpsByUserId(users.getUserId());   //当前登录人所有结算组织
        String deptidStr=""; //得到结算组织下所有部门deptId
        for(Department department:departments2){
            deptidStr+=department.getDeptId()+",";
        }
        String[] str=deptidStr.split(",");    //数组去重
        map.put("deptIds",str);
        map1.put("deptIds",str);
        List<Users> usersList=usersMapper.selectUserArrayByDeptId(map1);  //得到当前登录人所在结算组织部门（包括下级部门）的所有人员
        List list1=new ArrayList();
        for(Users u:usersList){
            list1.add(u.getUserId());
        }
        map.put("userIds",list1);
        map.put("approverStatus",ApprovalStatus);
        map1.put("userIds",list1);
        map1.put("approverStatus",ApprovalStatus);
        if(column!=null && inptext!=null){
            Map map2 = new HashMap();
            if( column.equals("BORROWER_USER") || column.equals("BORROWER_OPERATION_USER") || column.equals("APPROVER")){
                map2.put("userName",inptext);
                List<Users> usersList1 = usersMapper.selByUserNameAndDeptId(map2);
                String uids="";
                for(Users users2:usersList1){
                    uids+=users2.getUserId()+",";
                }
                String key=equipmentTransferService.lineToHump(column);

                map.put("column",column);
                map.put("smcolums",key);
                map.put("columsValue",uids.split(","));
                map1.put("column",column);
                map1.put("smcolums",key);
                map1.put("columsValue",uids.split(","));
            }  else if( column.equals("BORROWER_DETP_ID") || column.equals("LEND_DEPT_ID")){
                List<Department> departments = departmentMapper.selByLikeDeptName(inptext);
                String deptIdsArry="";
                for(Department department:departments){
                    deptIdsArry+=department.getDeptId()+",";
                }
                String key=equipmentTransferService.lineToHump(column);
                map.put("column",column);
                map.put("smcolums",key);
                map.put("columsValue",deptIdsArry.split(","));
                map1.put("column",column);
                map1.put("smcolums",key);
                map1.put("columsValue",deptIdsArry.split(","));
            }else{
                map.put("column",column);
                map.put("inptext",inptext);
                map1.put("column",column);
                map1.put("inptext",inptext);
            }
        }
        List<LimsEquipLend> limsEquipLends=limsEquipLendMapper.getAdministration(map);
        for(LimsEquipLend l:limsEquipLends){
            if (l.getBorrowerUser()!=null&&!l.getBorrowerUser().equals("")){  //借用人
                Users users1=usersMapper.findUsersByuserId(l.getBorrowerUser());
                if(users1!=null){
                    l.setBorrowerUser(users1.getUserName());
                }
            }
            if (l.getBorrowerOperationUser()!=null&&!l.getBorrowerOperationUser().equals("")){  //借用操作人
                Users users1=usersMapper.findUsersByuserId(l.getBorrowerOperationUser());
                if(users1!=null){
                    l.setBorrowerOperationUser(users1.getUserName());
                }
            }
            if (l.getBorrowerOperationUser()!=null&&!l.getBorrowerOperationUser().equals("")){  //借用操作人
                Users users1=usersMapper.findUsersByuserId(l.getBorrowerOperationUser());
                if(users1!=null){
                    l.setBorrowerUser(users1.getUserName());
                }
            }
            if (l.getBorrowerDetpId()!=null&&!l.getBorrowerDetpId().equals("")){  //借入部门
                Department  department=departmentMapper.getDeptById(l.getBorrowerDetpId());
                if(department!=null){
                    l.setBorrowerdeptName(department.getDeptName());
                }
            }
            if (l.getLendDeptId()!=null&&!l.getLendDeptId().equals("")){  //借出部门
                Department  department=departmentMapper.getDeptById(l.getLendDeptId());
                if(department!=null){
                    l.setLenddeptName(department.getDeptName());
                }
            }
            if(l.getApprover()!=null&&!l.getApprover().equals("")){
                Users users1=usersMapper.findUsersByuserId(l.getApprover());
                if(users1!=null){
                    l.setApprover(users1.getUserName());
                }
            }
        }
        map.put("approverStatus",ApprovalStatus);
        map.put("userIds",list1);
        map1.put("approverStatus",ApprovalStatus);
        map1.put("userIds",list1);
        Integer count=limsEquipLendMapper.count(map1);
        pageParams.setTotal(count);
        if(limsEquipLends!=null){
            limsJson.setData(limsEquipLends);
            limsJson.setCount(pageParams.getTotal());
            limsJson.setMsg("查询成功");
        }else{
            limsJson.setMsg("查询失败");
        }
        return limsJson;
    }


    /** 创建作者:   王穗穗
     * 创建日期:   13:05 2019/10/16
     * 方法介绍:   设备单编辑
     * 参数说明:   [request, limsEquipLend]
     * @return     com.xoa.util.LimsJson
     */
    @Override
    public LimsJson updeLendById(HttpServletRequest request, LimsEquipLend limsEquipLend) {
        LimsJson limsJson=new LimsJson(1,"err");
        if(limsEquipLend!=null){
            int count=limsEquipLendMapper.updateByPrimaryKeySelective(limsEquipLend);
            if(count>0) {
                limsJson.setMsg("编辑成功");
            }else{
                limsJson.setMsg("编辑失败");
            }
        }else{
            limsJson.setMsg("编辑失败");
        }
        return limsJson;
    }

    @Override
    public LimsJson getlendByid(Integer lendId) {
        LimsJson limsJson=new LimsJson(1,"err");
        if(lendId!=null){
            LimsEquipLend limsEquipLend=limsEquipLendMapper.selectByPrimaryKey(lendId);
            if(limsEquipLend.getBorrowerUser()!=null){
                Users users=usersMapper.findUsersByuserId(limsEquipLend.getBorrowerUser());
                limsEquipLend.setBowwerUserName(users.getUserName());
            }
            if(limsEquipLend.getBorrowerOperationUser()!=null){
                Users users=usersMapper.findUsersByuserId(limsEquipLend.getBorrowerOperationUser());
                limsEquipLend.setLendUserName(users.getUserName());
            }
            if(limsEquipLend!=null){
                limsJson.setObject(limsEquipLend);
                limsJson.setMsg("查询成功");
                limsJson.setCode(0);
            }else{
                limsJson.setMsg("查询失败");
            }
        }
        return limsJson;
    }

    @Override
    public LimsJson equipBorrowData(Integer page, Integer limit, Integer equipId, java.sql.Date borrowTime, java.sql.Date returnTime, String borrowerUser, String borrowerDetpId, String approverStatus, String returnStatus) {
        LimsJson limsJson=new LimsJson();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(limit);
        Map map=new HashMap();
        map.put("page", pageParams);
        map.put("equipId",equipId);
        map.put("borrowTime",borrowTime);
        map.put("returnTime",returnTime);
        map.put("borrowerDetpId",borrowerDetpId);
        map.put("approverStatus",approverStatus);
        map.put("returnStatus",returnStatus);
        map.put("borrowerUser",borrowerUser);
        List<LimsEquipLend> limsEquipLend=limsEquipLendMapper.equipBorrowData(map);
        for(LimsEquipLend limsEquipLend1:limsEquipLend){
            Users users=usersMapper.findUsersByuserId(limsEquipLend1.getBorrowerUser());
            if(users!=null){
                limsEquipLend1.setBorrowerUser(users.getUserName());
            }
            if (limsEquipLend1.getBorrowerDetpId()!=null&&!limsEquipLend1.getBorrowerDetpId().equals("")){  //借入部门
                Department  department=departmentMapper.getDeptById(limsEquipLend1.getBorrowerDetpId());
                if(department!=null){
                    limsEquipLend1.setBorrowerdeptName(department.getDeptName());
                }
            }
        }
        if(limsEquipLend!=null){
            limsJson.setCount(limsEquipLendMapper.equipBorrowCount(map));
            limsJson.setMsg("查询成功");
            limsJson.setData(limsEquipLend);
            limsJson.setCode(0);
        }else{
            limsJson.setMsg("查询失败");
            limsJson.setCode(1);
        }
        return limsJson;
    }

    @Override
    public LimsJson equipUseLogData(Integer page, Integer limit, Integer equipId, java.sql.Date borrowTime, java.sql.Date returnTime, String projectNo, String projectName, String borrowerUser) {
        LimsJson limsJson=new LimsJson();
        PageParams pageParams = new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(limit);
        Map map=new HashMap();
        map.put("page", pageParams);
        map.put("equipId",equipId);
        map.put("borrowTime",borrowTime);
        map.put("returnTime",returnTime);
        map.put("projectNo",projectNo);
        map.put("projectName",projectName);
        map.put("borrowerUser",borrowerUser);
        List<Map> limsEquipUselogs=limsEquipUselogMapper.equipUseLogData(map);
        for(int i=0;i<limsEquipUselogs.size();i++){
            String userId=limsEquipUselogs.get(i).get("BORROW_USER").toString();
            Users users=usersMapper.getUsersByuserId(userId);
            if (users!=null){
                limsEquipUselogs.get(i).put("BORROW_USER",users.getUserName());
            }
        }
        if(limsEquipUselogs!=null){
            limsJson.setCode(0);
            limsJson.setMsg("查询成功");
            limsJson.setCount(limsEquipUselogMapper.equipUseLogCount(map));
            limsJson.setData(limsEquipUselogs);
        }else{
            limsJson.setCode(1);
            limsJson.setMsg("查询失败");
        }
        return limsJson;
    }

    @Override
    public LimsJson Laboratory(HttpServletRequest request) {
        LimsJson limsJson=new LimsJson<>(1,"err");
        Users users = UserUtil.getUser(request);
        List<Department> allDepartment = departmentMapper.getAllDepartment();
        if(allDepartment!=null&&allDepartment.size()>0){
            limsJson.setData(allDepartment);
            limsJson.setCode(0);
            limsJson.setMsg("查询成功");
        }else{
            limsJson.setMsg("请添加实验室之后再进行操作");
            limsJson.setCode(1);
        }
        return limsJson;
    }


}
